$(function () {
    var queryUrl = '../toolslist/list';
    var Id = getQueryString('Id');
    if (Id) {
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        rownumWidth: 40,
        autoScroll: false,//当autoScroll和shrinkToFit均为false时，会出现行滚动条
        shrinkToFit: false,//是否列宽度自适应。true=适应 false=不适应
        colModel: [
            {label: '工装编码', name: 'toolsCode', index: 'TOOLS_CODE', width: 70,frozen: true},
            {label: '名称', name: 'name', index: 'NAME', width: 120,frozen: true},
            {label: 'ERP编码', name: 'erpCode', index: 'ERP_CODE', width: 80,frozen: true},
            {label: '图号', name: 'mapNo', index: 'MAP_NO', width: 120,frozen: true},
            {label: '自制图号', name: 'createNo', index: 'CREATE_NO', width: 120,frozen: true},
            {label: '型号规格', name: 'type', index: 'TYPE', width: 80},
            {label: '适用机型', name: 'applicableModel', index: 'APPLICABLE_MODEL', width: 80},
            {label: '现场装机总量', name: 'capacity', index: 'CAPACITY', width: 80},
            {label: '生产线', name: 'productLineName', index: 'PRODUCT_LINE', width: 80},
            {label: '使用工序', name: 'useProcedure', index: 'USE_PROCEDURE', width: 80},
            {
                label: '是否易损', name: 'isVulnerable', index: 'IS_VULNERABLE', width: 60, formatter: function (value) {
                    return value == '0' ?
                        '<span class="label label-danger">否</span>' :
                        '<span class="label label-success">是</span>';
                }
            },
            {label: '工装类别', name: 'typeName', index: 'TOOLS_TYPE', width: 70},
            {label: '管控方式', name: 'controlWayName', index: 'CONTROL_WAY', width: 100},
            {
                label: '当前进度', index: 'PROGRESS', width: 80,
                formatter: function (value, col, row) {
                    return sysEnums.SPARE_NEEDS_PLAN_PROGRESS[row.progress];
                }
            },
            {
                label: '审核详情', width: 60,sortable:false,  frozen : true,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.showReviewDetail(\"" + escape(JSON.stringify(row)) + "\")'>&nbsp;详情</button>";
                }
            },
            {name: 'progress', hidden: true},
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
        ]
    });
    $("#jqGrid").jqGrid('setFrozenColumns');//设置冻结列生效
    vm.getRoleList();
    vm.getDept();
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        },
    },
    callback: {
        beforeCheck: true,
    }

};
//部门树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    //此处treeNode 为当前节点
    var str = '';
    str = getAllChildrenNodes(treeObj, str);
    // 加上被选择节点自己
    str = str + ',' + treeObj.deptId;
    // 去掉最前面的逗号
    var ids = str.substring(1, str.length);
    vm.q.productLineIds = ids;
    vm.query();
}

// 递归，获取所有子节点
function getAllChildrenNodes(treeNode, result) {
    if (treeNode.isParent) {
        var childrenNodes = treeNode.children;
        if (childrenNodes) {
            for (var i = 0; i < childrenNodes.length; i++) {
                result += ',' + childrenNodes[i].deptId;
                result = getAllChildrenNodes(childrenNodes[i], result);
            }
        }
    }
    return result;
}


var vm = new Vue({
    el: '#rrapp',
    data: {
        isPrivilege: 0, // 是否是特权
        showList: true,
        title: null,
        toolslist: {
            controlWay: '',
            controlWayArray: [],
            isVulnerable: 0,
            toolsType: '',
            useProcedure: '',
            productLine: '',
            productLineName: '',
            capacity: 1,
            applicableModel: '',
            type: '',
            mapNo: '',
            toolsCode: '',
            name: '',
            id: '',
            toolsBaseId:''
        },
        ruleValidate: {
            name: [
                {required: true, message: '工装名称不能为空！', trigger: 'blur'}
            ],
            productLineName: [
                {required: true, message: '产线必选！', trigger: 'change'}
            ],
            useProcedure: [
                {required: true, message: '使用工序必填！', trigger: 'blur'}
            ]
        },
        q: {
            name: '',
            mapNo: '',
            type: '',
            productLineIds: '',
        },
        toolstypeList: [],
        toolscontrolwayList: [],
        //审核状态
        qualityApprovalStauts: 1,
        // 审核参数VO
        approveParam:{
            approveIdList: [],
            status: 1,
            remark: ''
        },
    },
    watch: {
        'toolslist.controlWayArray': function (val, oldval) {
            vm.toolslist.controlWay = vm.toolslist.controlWayArray.join(',');
        }
    },
    methods: {
        getToolsbaseSelect: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 工装清单',
                content: '../tools/toolsbaseSelect.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getToolsbase();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        vm.toolslist.name = res.name;
                        vm.toolslist.toolsCode = res.toolsCode;
                        vm.toolslist.mapNo = res.mapNo;
                        vm.toolslist.createNo = res.createNo;
                        vm.toolslist.type = res.type;
                        vm.toolslist.applicableModel = res.applicableModel;
                        vm.toolslist.toolsBaseId = res.id;
                        vm.toolslist.toolsType = res.toolsType;
                        vm.toolslist.isVulnerable = res.isVulnerable;
                        if(res.controlWay){
                            vm.toolslist.controlWayArray = res.controlWay.split(',');
                        }
                        layer.close(index);
                    }
                }
            })
        },
        //审核详情
        showReviewDetail: function (res) {
            var data = JSON.parse(unescape(res))
            Ajax.request({
                url: '../sysProcess/approve',
                params: {bussinessId: data.id},
                type: 'POST',
                successCallback: function (res) {
                    var approveProcessList = res.approveProcessList;
                    if (approveProcessList.length == 0) {
                        iview.Message.error("暂无审批记录");
                        return;
                    }
                    var dom = "<div class='details'><table>";
                    for (var i = 0; i < approveProcessList.length; i++) {
                        var approveProcess = approveProcessList[i];
                        dom += '<tr><td>' + approveProcess.approveDate + '</td>';
                        dom += '<td align="left">' + approveProcess.roleName + '-' + approveProcess.name + '： ' + sysEnums.CHECK_FLAG[approveProcess.status];
                        if (approveProcess.remark) {
                            dom += '<br />备注：' + approveProcess.remark;
                        }
                        dom += '</td></tr>'
                    }
                    dom += '</table></div>'
                    layer.open({
                        type: 1,
                        title: "审核详情",
                        closeBtn: 0,
                        area: ['500px'],
                        offset: '10vh',
                        shadeClose: true,
                        skin: 'yourclass',
                        content: dom
                    });
                }
            });
        },
        getRoleList: function () {
            Ajax.request({
                url: '../sys/user/isPrivilege',
                async: false,
                successCallback: function (r) {
                    vm.isPrivilege = r.isPrivilege;
                }
            });
        },
        exportData: function () {
            window.open('../toolslist/export');
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleError: function (err, file) {
            alert('导入失败');
        },
        goToolsFile: function () {
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            openWindow({
                type: 2,
                title: '<i class="fa fa-bars"></i> 工装档案',
                content: '../sys/ermsfile.html?moduleType=4&id=' + id
            })
        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.toolslist = {
                controlWay: '',
                controlWayArray: [],
                isVulnerable: '0',
                toolsType: '',
                useProcedure: '',
                productLine: '',
                productLineName: '',
                capacity: '1',
                applicableModel: '',
                type: '',
                mapNo: '',
                toolsCode: '',
                name: '',
                id: '',
                toolsBaseId:''
            };
            var date = new Date();
            vm.toolslist.toolsCode = 'FROCK_' + date.getFullYear() + (date.getMonth() + 1) + (date.getDate()) + date.getHours() + date.getMinutes() + date.getSeconds()
            vm.initData();
            vm.getTreeShow();
        },
        update: function (event) {
            var id = getSelectedRows("#jqGrid");
            if (id == null) {
                return;
            }
            var result = getSelectedRowData("#jqGrid");
            // 特权人员可以修改审批过的数据
            if (vm.isPrivilege == 0) {
                if (result.qualityApprovalStauts == '已审核') {
                    alert("当前审批已经通过，禁止更改！");
                    return;
                }
            }
            vm.showList = false;
            vm.title = "修改";
            vm.getInfo(id);
            vm.initData();
            vm.getTreeShow();
        },
        saveOrUpdate: function (event) {
            if (vm.toolslist.id == (null || '')) {
                Ajax.request({
                    url: "../toolslist/save",
                    params: JSON.stringify(vm.toolslist),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            } else {
                if ((vm.toolslist.qualityApprovalStauts == 0) || (vm.toolslist.qualityApprovalStauts == 2)) {
                    Ajax.request({
                        url: "../toolslist/update",
                        params: JSON.stringify(vm.toolslist),
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function (index) {
                                vm.reload();
                            });
                        }
                    });
                } else {
                    confirm('编辑后，将重新进行审批，确定修改？', function () {
                        Ajax.request({
                            url: "../toolslist/update",
                            params: JSON.stringify(vm.toolslist),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        });
                    });
                }
            }
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            var result = getSelectedRowData("#jqGrid");
            // 特权人员可以修改审批过的数据
            if (vm.isPrivilege == 0) {
                if (result.qualityApprovalStauts == '已审核') {
                    alert("当前审批已经通过，禁止更改！");
                    return;
                }
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../toolslist/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../toolslist/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.toolslist = r.toolslist;
                }
            });
        },
        reload: function (event) {
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: vm.q,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                mapNo: '',
                type: '',
                productLineIds: ''
            };
            deptZtree.cancelSelectedNode();
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        initData: function () {
            Ajax.request({
                url: "../toolstype/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.toolstypeList = r.list;
                }
            });
            Ajax.request({
                url: "../toolscontrolway/queryAll",
                async: true,
                successCallback: function (r) {
                    vm.toolscontrolwayList = r.list;
                }
            });
        },
        deptCheck: function () {
            var _this = this;
            var data = getSelectedRowData('#jqGrid');
            if (data.progress != 2) {
                alert('只有处于[部门审核]的计划才可以执行该操作！');
                return;
            }
            // 构建审批参数
            _this.approveParam = {
                approveIdList: [data.id],
                status: '1',
                remark: ''
            }
            openWindow({
                title: '工装审核',
                area: ['500px', '260px'],
                content: jQuery("#reviewLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    Ajax.request({
                        url: '../toolslist/review',
                        params: JSON.stringify(_this.approveParam),
                        contentType: "application/json",
                        type: 'POST',
                        successCallback: function (res) {
                            alert('审核成功!');
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        }
                    });
                }
            });
        },
        getDept: function () {
            //加载部门树
            Ajax.request({
                url: '../sys/user/loadLineList',
                async: true,
                successCallback: function (r) {
                    deptZtree = $.fn.zTree.init($("#deptTree"), deptSetting, r.list);
                    deptZtree.expandAll(true);
                }
            });
        },
        getTreeShow: function () {
            //加载分类树
            Ajax.request({
                url: '../sys/user/loadLineList',
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#categoryTree"), setting, r.list);
                    ztree.expandAll(true);
                    // console.log(vm.toolslist);
                    var node = ztree.getNodeByParam("deptId", vm.toolslist.productLine);
                    // console.log(node);
                    if (node) {
                        ztree.selectNode(node);
                        vm.toolslist.productLineName = node.name;
                    } else {
                        node = ztree.getNodeByParam("deptId", "0");
                        ztree.selectNode(node);
                        // vm.logicCourse.courseTypeName = node.name;
                    }
                }
            });
        },
        deptTreeShow: function () {
            openWindow({
                title: "选择生产线",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    let currentNode = nodes[0];
                    if (currentNode.deptType == 'DT_CJKSCX') {
                        if (currentNode.deptLevel != 3) {
                            alert("请选择产线");
                            return
                        }
                        // 设置产线ID和名称
                        vm.toolslist.productLine = currentNode.deptId;
                        vm.toolslist.productLineName = currentNode.name;
                        layer.close(index);
                    }
                }
            });
        }
    }
});
